﻿using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;

namespace Business {
    public class EmailBox {
        private readonly string _Hostname;
        private readonly int _Port;
        private readonly bool _UserSsl;
        private readonly string _Username;
        private readonly string _Password;

        public EmailBox(string hostname, int port, bool userSsl, string username, string password) {
            _Hostname = hostname;
            _Port = port;
            _UserSsl = userSsl;
            _Username = username;
            _Password = password;
        }

        public IEnumerable<Message> GetMessages(Func<MessageHeader, bool> filter) {
            using (var client = new Pop3Client()) {
                // Connect to the server
                client.Connect(_Hostname, _Port, _UserSsl);
                // 认证，新浪企业邮箱在Connect时声称支持apop认证，但实际上并未实现，所以强制使用明文
                //client.Authenticate(_Username, _Password, AuthenticationMethod.UsernameAndPassword);
                client.Authenticate(_Username, _Password);
                // 新浪企业邮箱只提供最新的100封邮件
                int messageCount = client.GetMessageCount();
                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                foreach (var i in Enumerable.Range(1, messageCount)) {
                    if (filter != null) {
                        var header = client.GetMessageHeaders(i);
                        Console.WriteLine(header.Subject);
                        var match = filter.Invoke(header);
                        if (!match)
                            continue;
                    }
                    yield return client.GetMessage(i);
                }

            }
        }
    }
}